import { Collapse, Form, Input, InputNumber, Radio, Select } from "antd";
import { CSSProperties, useEffect, useMemo, useState } from "react";
import { ComponentConfig, ComponentSetter, useComponentConfigStore } from "@/stores/low-editor-comps-conf";
import { useComponentsStore, getComponentById } from "@/stores/edit-pages-store";
import CssEditor from "../CssEditor";
import { camelCase, debounce, divide } from "lodash-es";
import StyleToObject from "style-to-object";
import { GeometryUnitInputNumber } from "../selectors/GeometryUnitInputNumber";
import { setThemeCssClassStylesheet, setCustomClassStylesheet } from "@/pages/lowCodeEditorPlus/utils/styleOperation";
import "./index.scss";
export function ComponentStyle() {
  const [basicForm] = Form.useForm();
  const [cooptedForm] = Form.useForm();

  const {
    curComponentId,
    curComponent,
    updateComponentStyles,
    updateComponentCustomStyle,
    updateComponentCooptedStyles,
    schema,
  } = useComponentsStore();
  const { flatComponentConfig } = useComponentConfigStore();
  const componentConfig = flatComponentConfig();

  if (!curComponentId || !curComponent) return null;
  const [basicData, setBasicData] = useState<Record<string, any>>({});
  useEffect(() => {
    basicForm.resetFields();
    cooptedForm.resetFields();

    /*获取配置的初始值*/
    const basicDefaultValues = (componentConfig[curComponent.name]?.basicStyleSetter ?? []).reduce(
      (sum, cell) => {
        if (cell?.defaultValue) {
          sum[cell.name] = cell.defaultValue;
        }
        if (cell?.siblings) {
          cell.siblings.forEach(sItem => {
            sum[sItem.name] = sItem.defaultValue;
          });
        }
        return sum;
      },
      {} as Record<string, any>
    );

    const initBasicData = { ...basicForm.getFieldsValue(), ...basicDefaultValues,...curComponent?.styles };
    setBasicData(initBasicData)
    const cooptedData = {...cooptedForm.getFieldsValue(), ...curComponent?.themeCss?.cooptedStyle};
    
    basicForm.setFieldsValue({ ...initBasicData});
    cooptedForm.setFieldsValue({ ...cooptedData});

    setCss(objectToCSSStr(curComponent?.customClassStyle ?? {}));
  }, [curComponentId]);
  
  function renderFormElement(setter: ComponentSetter) {
    const { name, type, options, props, siblings = [], siblingsShowValue } = setter;

    let cell = <></>;
    if (type === "select") {
      cell = <Select options={options} />;
    } else if (type === "input") {
      cell = <Input />;
    } else if (type === "inputNumber") {
      // return <InputNumber />;
      cell = <GeometryUnitInputNumber />;
    } else if (type === "radio") {
      cell = props.useRenderOption ? (
        <Radio.Group optionType={props.optionType} buttonStyle={props.buttonStyle}>
          {options}
        </Radio.Group>
      ) : (
        <Radio.Group options={options} optionType={props.optionType} buttonStyle={props.buttonStyle} />
      );
    }
    const showSiblings = siblings.length > 0 && (basicData[name]===siblingsShowValue && !!siblingsShowValue)
    

    return (
      <div key={setter.name}>
        <Form.Item key={setter.name} name={setter.name} label={setter.label}>
          {cell}
        </Form.Item>
        {showSiblings && (
          <div className="displaySiblings bg-gray-200 rounded-md p-1">
            {siblings.map(sItem => renderFormElement(sItem))}
          </div>
        )}
      </div>
    );
  }

  const [css, setCss] = useState<string>("");

  function objectToCSSStr(css: Record<string, any>) {
    let str = "";
    for (let key in css) {
      let value = css[key];
      if (!value) {
        continue;
      }
      str += `\t${key}: ${value};\n`;
    }
    return str;
  }

  function basicValueChange(changeValues: CSSProperties) {
    if (curComponentId) {
      const doDisplay = changeValues.display
      if(doDisplay){
        if(doDisplay === "flex"){
          changeValues = {...changeValues, flexDirection: "column", flexWrap: "nowrap"}
          basicForm.setFieldValue("alignItems", "stretch")
        }else{
          changeValues = {...changeValues, flexDirection: undefined, justifyContent: undefined, alignItems:"stretch", flexWrap: undefined}
        }
      }
      setBasicData(prevData => ({
        ...prevData,
        ...changeValues
       }))
      updateComponentStyles(curComponentId, changeValues);
    }
  }
  function cooptedValueChange(changeValues: CSSProperties) {
    if (curComponentId) {
      updateComponentCooptedStyles(curComponentId, "cooptedStyle", changeValues);
      const style = getComponentById(curComponentId, schema)?.themeCss;
      setThemeCssClassStylesheet({ style, id: curComponentId }); //设置stylesheet
    }
  }

  const handleEditorChange = debounce(async value => {
    let css: Record<string, any> = {};
    try {
      StyleToObject(value, (name, value) => {
        css[name] = value;
      });

      updateComponentCustomStyle(curComponentId, css); //更新store
      setCustomClassStylesheet({ style: css, id: curComponentId }); //设置stylesheet
    } catch (e) {
      console.log(e);
    }
  }, 500);

  const menuItems = [
    {
      key: "basicStyle",
      label: "基本样式",
      children: (
        <Form
          form={basicForm}
          onValuesChange={basicValueChange}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          labelAlign="left"
          labelWrap
          colon={false}
          className="smallText"
        >
          {componentConfig[curComponent.name]?.basicStyleSetter?.map(setter =>
            // <Form.Item key={setter.name} name={setter.name} label={setter.label}>
            // {renderFormElement(setter)}
            // </Form.Item>
            renderFormElement(setter)
          )}
        </Form>
      ),
    },
    {
      key: "cooptedStyle",
      label: "增选样式",
      children: (
        <Form
          form={cooptedForm}
          onValuesChange={cooptedValueChange}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          labelAlign="left"
          labelWrap
          colon={false}
          className="smallText"
        >
          {componentConfig[curComponent.name]?.cooptedStyleSetter?.map(setter =>
            // <Form.Item key={setter.name} name={setter.name} label={setter.label}>
            renderFormElement(setter)
            // </Form.Item>
          )}
        </Form>
      ),
    },
    {
      key: "customStyle",
      label: "自定义样式",
      children: (
        <div className="h-52 border flex-wrap gap-3 ">
          <CssEditor value={css} onChange={handleEditorChange} />
        </div>
      ),
    },
  ];
  return (
    <Collapse
      defaultActiveKey={menuItems.map(item => item.key)}
      ghost
      items={menuItems}
      expandIconPosition="end"
      className="classic headerGray"
    />
  );
}
